import numpy as np
from shapely.geometry import Polygon, LineString

def generate_grid_waypoints(polygon_coords, flight_params):
    """
    根据多边形坐标和飞行参数生成栅格航线点
    polygon_coords: [[lon, lat], [lon, lat], ...]
    """
    # 1. 创建多边形对象
    poly = Polygon(polygon_coords)
    
    # 2. 获取最小外接矩形
    minx, miny, maxx, maxy = poly.bounds
    
    # 3. 计算航线间距（基于相机参数和重叠度）
    # 使用简化公式: 航线间距 = 飞行高度 * (1 - 重叠度/100) * 0.8
    # 0.8是一个经验系数，考虑相机视场角
    flight_height = flight_params['altitude'] - flight_params.get('egm96_offset', 7.3)  # 实际飞行高度
    overlap_w = flight_params.get('ortho_camera_overlap_w', 60)  # 旁向重叠
    line_spacing = flight_height * (1 - overlap_w/100) * 0.8  # 航线间距，单位米
    
    # 4. 转换间距为经纬度（近似）
    # 纬度1度约等于111km，经度1度在不同纬度不同，约等于111km*cos(lat)
    avg_lat = (miny + maxy) / 2
    lat_spacing = line_spacing / 111000  # 转换为度
    lon_spacing = line_spacing / (111000 * np.cos(np.radians(avg_lat)))
    
    # 5. 确定航线方向
    direction = int(flight_params.get('direction', 11))
    horizontal_flight = (direction == 11)  # 默认为水平方向飞行
    
    # 6. 生成平行航线
    lines = []
    waypoints = []
    
    if horizontal_flight:
        # 水平方向航线
        y_values = np.arange(miny, maxy + lat_spacing, lat_spacing)
        for i, y in enumerate(y_values):
            if i % 2 == 0:  # 从左往右
                line = LineString([(minx, y), (maxx, y)])
            else:  # 从右往左
                line = LineString([(maxx, y), (minx, y)])
            lines.append(line)
    else:
        # 垂直方向航线
        x_values = np.arange(minx, maxx + lon_spacing, lon_spacing)
        for i, x in enumerate(x_values):
            if i % 2 == 0:  # 从下往上
                line = LineString([(x, miny), (x, maxy)])
            else:  # 从上往下
                line = LineString([(x, maxy), (x, miny)])
            lines.append(line)
    
    # 7. 裁剪航线，只保留多边形内的部分
    clipped_lines = []
    for line in lines:
        if line.intersects(poly):
            intersection = line.intersection(poly)
            if intersection.geom_type == 'MultiLineString':
                for geom in intersection.geoms:
                    clipped_lines.append(geom)
            else:
                clipped_lines.append(intersection)
    
    # 8. 提取航点坐标
    for i, line in enumerate(clipped_lines):
        coords = list(line.coords)
        # 确保S型路径的连续性，保持交替方向
        if i > 0 and i % 2 == 1:
            coords = coords[::-1]  # 反转坐标
            
        for coord in coords:
            waypoints.append([coord[0], coord[1]])
    
    # 9. 确保首尾点不重复，但如果少于2个点则使用原始多边形
    if len(waypoints) < 2:
        print("警告：生成的栅格航线点不足，使用多边形边界点作为航线...")
        return [[c[0], c[1]] for c in polygon_coords]
    
    # 10. 检查是否需要闭合路径
    if flight_params.get('close_path', False):
        waypoints.append(waypoints[0])
    
    return waypoints